import Icon from "@/components/Icon";
import { getUserChannels } from "@/store/actions/home";
import { useInitialState } from "@/utils/use-initial-state";
import { Popup, Tabs } from "antd-mobile";
import Channels from "./components/Channels";
import { useState } from "react";
import styles from "./index.module.scss";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/types/store";
import ArticleList from "./components/ArticleList";
import { useHistory } from "react-router-dom";

const Home = () => {
    const { userChannel } = useInitialState(getUserChannels, "home");
    const [visible, setVisible] = useState(false);
    // 打开编辑频道弹层
    const onChannelOpen = () => {
        setVisible(true);
    };
    // 关闭编辑频道弹层
    const onChannelClose = () => {
        setVisible(false);
    };
    // 获得高亮
    const dispatch = useDispatch();
    const { channelActiveKey } = useSelector((state: RootState) => state.home);
    // 切换频道
    const onTabChange = (key: string) => {
        dispatch({ type: "home/changeTab", payload: key });
    };
    const history = useHistory();
    return (
        <div className={styles.root}>
            {/* 延迟渲染 Tabs，解决 tab 高亮位置错误 */}
            {userChannel.length > 0 && (
                <Tabs
                    className="tabs"
                    activeKey={channelActiveKey}
                    onChange={onTabChange}
                    activeLineMode="fixed">
                    {userChannel.map((item) => (
                        <Tabs.Tab forceRender title={item.name} key={item.id}>
                            {/* 在每个 Tabs.TabPane 中渲染文章列表组件 */}
                            <ArticleList channelId={item.id} />
                        </Tabs.Tab>
                    ))}
                </Tabs>
            )}
            <div className="tabs-opration">
                <div className="tabs-linear">
                    <Icon
                        type="iconbtn_search"
                        onClick={() => history.push("/search")}
                    />
                    <Icon type="iconbtn_channel" onClick={onChannelOpen} />
                </div>
            </div>
            <Popup
                visible={visible}
                onMaskClick={onChannelClose}
                position="right"
                className="channel-popup">
                <Channels onClose={onChannelClose} />
            </Popup>
        </div>
    );
};

export default Home;
